import React, { useState, useEffect } from "react";
import {
  Card,
  List,
  Badge,
  Button,
  Tag,
  Progress,
  Row,
  Col,
  Statistic,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  message,
  Tabs,
  Empty,
  Spin,
  Space,
  Tooltip,
  Dropdown,
  Menu,
} from "antd";
import {
  ClockCircleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  CalendarOutlined,
  ReloadOutlined,
  MoreOutlined,
  PlayCircleOutlined,
  StopOutlined,
} from "@ant-design/icons";
import { taskApi, Task, TaskStats } from "../../services/taskService";
import moment from "moment";
import "./TaskQueue.less";

const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;

const TaskQueue: React.FC = () => {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [upcomingTasks, setUpcomingTasks] = useState<Task[]>([]);
  const [statistics, setStatistics] = useState<TaskStats>({
    total: 0,
    pending: 0,
    processing: 0,
    completed: 0,
    overdue: 0,
    highPriority: 0,
  });
  const [loading, setLoading] = useState(false);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [activeTab, setActiveTab] = useState("pending");
  const [selectedTask, setSelectedTask] = useState<Task | null>(null);
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();

  useEffect(() => {
    loadTasks();
    loadStatistics();
    loadUpcomingTasks();
  }, []);

  const loadTasks = async (status?: number) => {
    try {
      setLoading(true);
      const result = await taskApi.getTasks({
        status: status,
        page: 1,
        size: 50,
      });
      if (result.code === 0) {
        setTasks(result.data.list || result.data);
        console.log("✅ 任务数据加载成功", result.data);
      } else {
        message.error(result.message || "加载任务失败");
      }
    } catch (error: any) {
      console.error("❌ 加载任务失败:", error);
      message.error(error.message || "加载任务失败");
    } finally {
      setLoading(false);
    }
  };

  const loadStatistics = async () => {
    try {
      const result = await taskApi.getStats();
      if (result.code === 0) {
        setStatistics(result.data);
        console.log("✅ 任务统计加载成功", result.data);
      }
    } catch (error) {
      console.error("❌ 获取任务统计失败:", error);
    }
  };

  const loadUpcomingTasks = async () => {
    try {
      const result = await taskApi.getUpcomingTasks(7);
      if (result.code === 0) {
        setUpcomingTasks(result.data);
        console.log("✅ 即将到期任务加载成功", result.data);
      }
    } catch (error) {
      console.error("❌ 获取即将到期任务失败:", error);
    }
  };

  const handleTabChange = (key: string) => {
    setActiveTab(key);
    let status: number | undefined;
    switch (key) {
      case "all":
        status = undefined;
        break;
      case "pending":
        status = 1;
        break;
      case "processing":
        status = 2;
        break;
      case "completed":
        status = 3;
        break;
      case "overdue":
        status = 4;
        break;
      default:
        status = undefined;
    }
    loadTasks(status);
  };

  const updateTaskStatus = async (taskId: number, status: number) => {
    try {
      const result = await taskApi.updateTask(taskId, { status });
      if (result.code === 0) {
        message.success("任务状态更新成功");
        loadTasks();
        loadStatistics();
      } else {
        message.error(result.message || "更新任务状态失败");
      }
    } catch (error: any) {
      console.error("❌ 更新任务状态失败:", error);
      message.error(error.message || "更新任务状态失败");
    }
  };

  const completeTask = async (taskId: number) => {
    try {
      const result = await taskApi.completeTask(taskId);
      if (result.code === 0) {
        message.success("任务已完成");
        loadTasks();
        loadStatistics();
      } else {
        message.error(result.message || "完成任务失败");
      }
    } catch (error: any) {
      console.error("❌ 完成任务失败:", error);
      message.error(error.message || "完成任务失败");
    }
  };

  const deleteTask = async (taskId: number) => {
    try {
      const result = await taskApi.deleteTask(taskId);
      if (result.code === 0) {
        message.success("任务已删除");
        loadTasks();
        loadStatistics();
      } else {
        message.error(result.message || "删除任务失败");
      }
    } catch (error: any) {
      console.error("❌ 删除任务失败:", error);
      message.error(error.message || "删除任务失败");
    }
  };

  const createTask = async (values: any) => {
    try {
      const result = await taskApi.createTask({
        ...values,
        dueTime: values.dueTime
          ? values.dueTime.format("YYYY-MM-DD HH:mm:ss")
          : null,
        priority: values.priority || 2,
        status: 1,
      });
      if (result.code === 0) {
        message.success("任务创建成功");
        setCreateModalVisible(false);
        form.resetFields();
        loadTasks();
        loadStatistics();
      } else {
        message.error(result.message || "创建任务失败");
      }
    } catch (error: any) {
      console.error("❌ 创建任务失败:", error);
      message.error(error.message || "创建任务失败");
    }
  };

  const updateTask = async (values: any) => {
    if (!selectedTask) return;

    try {
      const result = await taskApi.updateTask(selectedTask.id, {
        ...values,
        dueTime: values.dueTime
          ? values.dueTime.format("YYYY-MM-DD HH:mm:ss")
          : null,
      });
      if (result.code === 0) {
        message.success("任务更新成功");
        setEditModalVisible(false);
        setSelectedTask(null);
        editForm.resetFields();
        loadTasks();
        loadStatistics();
      } else {
        message.error(result.message || "更新任务失败");
      }
    } catch (error: any) {
      console.error("❌ 更新任务失败:", error);
      message.error(error.message || "更新任务失败");
    }
  };

  const handleEdit = (task: Task) => {
    setSelectedTask(task);
    editForm.setFieldsValue({
      ...task,
      dueTime: task.dueTime ? moment(task.dueTime) : null,
    });
    setEditModalVisible(true);
  };

  const getStatusText = (status: number) => {
    switch (status) {
      case 1:
        return "待处理";
      case 2:
        return "进行中";
      case 3:
        return "已完成";
      case 4:
        return "已过期";
      default:
        return "未知";
    }
  };

  const getStatusColor = (status: number) => {
    switch (status) {
      case 1:
        return "default";
      case 2:
        return "processing";
      case 3:
        return "success";
      case 4:
        return "error";
      default:
        return "default";
    }
  };

  const getPriorityText = (priority: number) => {
    switch (priority) {
      case 1:
        return "低";
      case 2:
        return "中";
      case 3:
        return "高";
      case 4:
        return "紧急";
      default:
        return "普通";
    }
  };

  const getPriorityColor = (priority: number) => {
    switch (priority) {
      case 1:
        return "green";
      case 2:
        return "blue";
      case 3:
        return "orange";
      case 4:
        return "red";
      default:
        return "default";
    }
  };

  const getDaysUntilDue = (dueTime: string) => {
    const due = moment(dueTime);
    const now = moment();
    return due.diff(now, "days");
  };

  const renderTaskItem = (task: Task) => {
    const daysLeft = task.dueTime ? getDaysUntilDue(task.dueTime) : null;
    const isOverdue = daysLeft !== null && daysLeft < 0;
    const isUrgent = daysLeft !== null && daysLeft <= 1 && daysLeft >= 0;

    const menuItems = (
      <Menu>
        {task.status === 1 && (
          <Menu.Item
            key="start"
            icon={<PlayCircleOutlined />}
            onClick={() => updateTaskStatus(task.id, 2)}
          >
            开始任务
          </Menu.Item>
        )}
        {task.status === 2 && (
          <Menu.Item
            key="complete"
            icon={<CheckCircleOutlined />}
            onClick={() => completeTask(task.id)}
          >
            完成任务
          </Menu.Item>
        )}
        <Menu.Item
          key="edit"
          icon={<EditOutlined />}
          onClick={() => handleEdit(task)}
        >
          编辑任务
        </Menu.Item>
        <Menu.Divider />
        <Menu.Item
          key="delete"
          danger
          icon={<DeleteOutlined />}
          onClick={() => {
            Modal.confirm({
              title: "确认删除",
              content: "确定要删除这个任务吗？",
              onOk: () => {
                deleteTask(task.id);
              },
            });
          }}
        >
          删除任务
        </Menu.Item>
      </Menu>
    );

    return (
      <List.Item
        key={task.id}
        className={`task-item ${isOverdue ? "overdue" : ""} ${isUrgent ? "urgent" : ""}`}
        actions={[
          <Dropdown overlay={menuItems} trigger={["click"]}>
            <Button type="text" icon={<MoreOutlined />} />
          </Dropdown>,
        ]}
      >
        <List.Item.Meta
          title={
            <Space>
              <span className="task-title">{task.title}</span>
              <Tag color={getStatusColor(task.status)}>
                {getStatusText(task.status)}
              </Tag>
              <Tag color={getPriorityColor(task.priority)}>
                {getPriorityText(task.priority)}
              </Tag>
              {task.autoGenerated && <Tag color="cyan">自动生成</Tag>}
            </Space>
          }
          description={
            <div className="task-description">
              <p>{task.description}</p>
              <Space className="task-meta">
                <span>
                  <ClockCircleOutlined />
                  创建时间: {moment(task.createTime).format("MM-DD HH:mm")}
                </span>
                {task.dueTime && (
                  <span
                    className={
                      isOverdue ? "overdue-text" : isUrgent ? "urgent-text" : ""
                    }
                  >
                    <CalendarOutlined />
                    截止时间: {moment(task.dueTime).format("MM-DD HH:mm")}
                    {daysLeft !== null && (
                      <span className="days-left">
                        {isOverdue
                          ? `(已过期 ${Math.abs(daysLeft)} 天)`
                          : daysLeft === 0
                            ? "(今天截止)"
                            : `(还有 ${daysLeft} 天)`}
                      </span>
                    )}
                  </span>
                )}
                {task.sourceType && task.sourceId && (
                  <span>
                    来源: {task.sourceType} #{task.sourceId}
                  </span>
                )}
              </Space>
            </div>
          }
        />
      </List.Item>
    );
  };

  return (
    <div className="task-queue">
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={4}>
          <Card>
            <Statistic
              title="总任务"
              value={statistics.total}
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="待处理"
              value={statistics.pending}
              valueStyle={{ color: "#1890ff" }}
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="进行中"
              value={statistics.processing}
              valueStyle={{ color: "#faad14" }}
              prefix={<PlayCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="已完成"
              value={statistics.completed}
              valueStyle={{ color: "#52c41a" }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="已过期"
              value={statistics.overdue}
              valueStyle={{ color: "#f5222d" }}
              prefix={<ExclamationCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="高优先级"
              value={statistics.highPriority}
              valueStyle={{ color: "#722ed1" }}
              prefix={<ExclamationCircleOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 主要内容 */}
      <Card
        title="任务队列"
        extra={
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setCreateModalVisible(true)}
            >
              新建任务
            </Button>
            <Button
              icon={<ReloadOutlined />}
              onClick={() => {
                loadTasks();
                loadStatistics();
                loadUpcomingTasks();
              }}
            >
              刷新
            </Button>
          </Space>
        }
      >
        <Tabs activeKey={activeTab} onChange={handleTabChange}>
          <TabPane tab={`全部 (${statistics.total})`} key="all" />
          <TabPane tab={`待处理 (${statistics.pending})`} key="pending" />
          <TabPane tab={`进行中 (${statistics.processing})`} key="processing" />
          <TabPane tab={`已完成 (${statistics.completed})`} key="completed" />
          <TabPane tab={`已过期 (${statistics.overdue})`} key="overdue" />
        </Tabs>

        <Spin spinning={loading}>
          {tasks.length > 0 ? (
            <List
              dataSource={tasks}
              renderItem={renderTaskItem}
              pagination={{
                pageSize: 20,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
              }}
            />
          ) : (
            <Empty description="暂无任务" />
          )}
        </Spin>
      </Card>

      {/* 创建任务Modal */}
      <Modal
        title="创建新任务"
        open={createModalVisible}
        onCancel={() => {
          setCreateModalVisible(false);
          form.resetFields();
        }}
        footer={null}
      >
        <Form form={form} onFinish={createTask} layout="vertical">
          <Form.Item
            name="title"
            label="任务标题"
            rules={[{ required: true, message: "请输入任务标题" }]}
          >
            <Input placeholder="请输入任务标题" />
          </Form.Item>
          <Form.Item name="description" label="任务描述">
            <TextArea rows={3} placeholder="请输入任务描述" />
          </Form.Item>
          <Form.Item
            name="taskType"
            label="任务类型"
            rules={[{ required: true, message: "请选择任务类型" }]}
          >
            <Select placeholder="请选择任务类型">
              <Option value="grading">批改作业</Option>
              <Option value="reminder">提醒</Option>
              <Option value="report">报告</Option>
              <Option value="exam">考试</Option>
              <Option value="assignment">作业</Option>
            </Select>
          </Form.Item>
          <Form.Item name="priority" label="优先级" initialValue={2}>
            <Select>
              <Option value={1}>低</Option>
              <Option value={2}>中</Option>
              <Option value={3}>高</Option>
              <Option value={4}>紧急</Option>
            </Select>
          </Form.Item>
          <Form.Item name="dueTime" label="截止时间">
            <DatePicker
              showTime
              format="YYYY-MM-DD HH:mm"
              style={{ width: "100%" }}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                创建任务
              </Button>
              <Button
                onClick={() => {
                  setCreateModalVisible(false);
                  form.resetFields();
                }}
              >
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑任务Modal */}
      <Modal
        title="编辑任务"
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false);
          setSelectedTask(null);
          editForm.resetFields();
        }}
        footer={null}
      >
        <Form form={editForm} onFinish={updateTask} layout="vertical">
          <Form.Item
            name="title"
            label="任务标题"
            rules={[{ required: true, message: "请输入任务标题" }]}
          >
            <Input placeholder="请输入任务标题" />
          </Form.Item>
          <Form.Item name="description" label="任务描述">
            <TextArea rows={3} placeholder="请输入任务描述" />
          </Form.Item>
          <Form.Item
            name="taskType"
            label="任务类型"
            rules={[{ required: true, message: "请选择任务类型" }]}
          >
            <Select placeholder="请选择任务类型">
              <Option value="grading">批改作业</Option>
              <Option value="reminder">提醒</Option>
              <Option value="report">报告</Option>
              <Option value="exam">考试</Option>
              <Option value="assignment">作业</Option>
            </Select>
          </Form.Item>
          <Form.Item name="priority" label="优先级">
            <Select>
              <Option value={1}>低</Option>
              <Option value={2}>中</Option>
              <Option value={3}>高</Option>
              <Option value={4}>紧急</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select>
              <Option value={1}>待处理</Option>
              <Option value={2}>进行中</Option>
              <Option value={3}>已完成</Option>
              <Option value={4}>已过期</Option>
            </Select>
          </Form.Item>
          <Form.Item name="dueTime" label="截止时间">
            <DatePicker
              showTime
              format="YYYY-MM-DD HH:mm"
              style={{ width: "100%" }}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                更新任务
              </Button>
              <Button
                onClick={() => {
                  setEditModalVisible(false);
                  setSelectedTask(null);
                  editForm.resetFields();
                }}
              >
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default TaskQueue;
